import { useState, useEffect, useRef } from 'react'
import './index.scss'

function Swiper(props) {
	const [duration, setDuration] = useState('300ms')
	const [transform, setTransform] = useState(null)
	const [curr, setCurr] = useState(0)
	const [startX, setStartX] = useState(0)
	const [startY, setStartY] = useState(0)
	const [isTimer, setTimer] = useState(true)

	let width, count, timer = useRef(), threshold = 50
	const myRef = useRef(null)
	if (myRef.current) {
		width = myRef.current.offsetWidth
	}
	const list = ['33', '1', '22', '33', '1']
	const li = list.map((item, index) => {
		return <li style={{ width: width + 'px' }} className={curr + 1 === index ? 'active' : ''} key={index}>
			<img src={require("../../img/" + item + "-400x300.jpg")} alt="" />
		</li>
	})
	count = list.length - 2
	// 它在第一次渲染之后和每次更新之后都会执行
	useEffect(() => {
		setTransform(-myRef.current.offsetWidth)
	}, [])
	useEffect(() => {
		if (props.auto && isTimer) {
			timer.current = setTimeout(() => {
				if (curr > count - 2) {
					setTimeout(() => {
						setDuration('none')
						setCurr(0)
						show(0)
					}, 300)
				} else {
					setCurr(curr + 1)
				}
				show(curr + 1)
			}, 4000)
		}
		if (!isTimer) {
			clearTimeout(timer.current)
		}
		return () => {
			clearTimeout(timer.current)
		}
	})
	const ontouchstart = (e) => {
		setStartX(e.changedTouches[0].pageX)
		setStartY(e.changedTouches[0].pageY)
		setTimer(false)
	}

	const ontouchmove = (e) => {
		let moveX = e.changedTouches[0].pageX,
			moveY = e.changedTouches[0].pageY,
			distanceX = moveX - startX, distanceY = moveY - startY

		if (Math.abs(distanceX) > Math.abs(distanceY)) {
			setTransform(distanceX - (curr + 1) * width)
		}
	}

	const ontouchend = (e) => {
		let endX = e.changedTouches[0].pageX,
			distance = endX - startX

		if (distance >= threshold) {
			show(curr - 1)
			setCurr(curr - 1)
			if (curr === 0) {
				setTimeout(() => {
					setDuration('none')
					show(count - 1)
					setCurr(count - 1)
				}, 300)
			}
		} else if (distance < -threshold) {
			show(curr + 1)
			setCurr(curr + 1)
			if (curr > count - 2) {
				setTimeout(() => {
					setDuration('none')
					show(0)
					setCurr(0)
				}, 300)
			}
		} else {
			show(curr)
		}
		if (props.auto) {
			setTimer(true)
		}
	}

	const show = (idx) => {
		setTransform(-(idx + 1) * width)
		if (idx === 0 || count - 1 === 2) {
			setTimeout(() => {
				setDuration('300ms')
			}, 100)
		} else {
			setDuration('300ms')
		}
	}

	return (
		<div>
			<h1>Hello, {props.name}</h1>
			<div ref={myRef} className="swiper" onTouchStart={ontouchstart} onTouchMove={ontouchmove} onTouchEnd={ontouchend}>
				<ul style={{ width: width * (count + 2) + 'px', transform: 'translate3d(' + transform + 'px,0,0)', transition: duration }}>
					{li}
				</ul>
			</div>
		</div>
	)
}

export default Swiper